const express = require("express");
const pool = require("../pool.js");
const { getToken } = require("../utils/index.js");

const adminRouter = express.Router();
module.exports = adminRouter;
// 管理员登录
adminRouter.post("/login", (req, res, next) => {
  var aname = req.body.aname;
  var apwd = req.body.apwd;
  var sql = "SELECT aid FROM admin where aname=? and apwd=MD5(?)";
  pool.query(sql, [aname, apwd], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      let token = getToken({ aid: r[0].aid });
      // 前端要想拿到后端请求头中的数据，需要暴露它写入Access-Control-Expose-Headers
      res.setHeader("Access-Control-Expose-Headers", "authorization");
      res.setHeader("authorization", token);

      res.send({ code: 200, msg: "登录成功" });
    } else {
      res.send({ code: 201, msg: "登录失败" });
    }
  });
});

// 管理员修改密码
adminRouter.put("/update", (req, res, next) => {
  var aname = req.body.aname;
  var apwd = req.body.apwd;
  var sql1 = "SELECT aid FROM admin where aname=?";
  pool.query(sql1, [aname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      var sql2 = `update admin set apwd=MD5(?) where aname=?`;
      pool.query(sql2, [apwd, aname], (err, r) => {
        if (err) {
          next(err);
          return;
        }
        res.send({ code: 200, msg: "修改密码成功" });
      });
    } else {
      res.send({ code: 201, msg: "管理员不存在" });
    }
  });
});

// 管理员注册
adminRouter.post("/register", (req, res, next) => {
  var aname = req.body.aname;
  var apwd = req.body.apwd;
  if (aname == "" || apwd == "") {
    res.send({ code: 202, msg: "输入不可为空！" });
    return;
  }
  if (!/^\w{6,12}$/.test(apwd)) {
    res.send({ code: 203, msg: "密码格式不正确" });
    return;
  }
  if (
    /[(\u4e00-\u9fa5)(\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3010|\u3011|\u007e)]/.test(
      aname
    )
  ) {
    res.send({ code: 204, msg: "不可用中文及标点！" });
    return;
  }
  var sql1 = "SELECT aid FROM admin where aname=?";
  pool.query(sql1, [aname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      res.send({ code: 201, msg: "管理员已存在" });
    } else {
      var sql2 = `INSERT INTO admin VALUES(replace(UUID(),'-',''),?,MD5(?))`;
      pool.query(sql2, [aname, apwd], (err, r) => {
        if (err) {
          next(err);
          return;
        }
        res.send({ code: 200, msg: "管理员注册成功" });
      });
    }
  });
});
